package com.ghsc.ghxc.jsb.ui.live.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityShareListBinding
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialChildInfoBean
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialInfoBean
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareLiveAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareSourceAttachment
import com.ghsc.ghxc.jsb.ui.mall.bean.MaterialBean
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.view.NotDataView
import com.google.gson.Gson
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import com.netease.yunxin.kit.conversationkit.ui.bean.ExtDataBean
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.activity
 * 类名：ShareGroupListActivity
 * 创建时间：2024/5/11 15:11
 * 创建人 @author： xiaolin
 * 描述 ：Todo...分享群
 */
class ShareGroupListActivity : BaseVMActivity<ShareListViewModel, ActivityShareListBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_share_list
    }



    override fun attachVMClass(): Class<ShareListViewModel>? {
        return ShareListViewModel::class.java
    }

    private val mAdapter: SearchChatAdapter by lazy { SearchChatAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var keyword:String=""

    var bundle : Bundle?=null
    var url :String= ""
    var liveID :String =""
    var userNick :String =""
    var userAvatar :String =""
    var coverUrl :String =""
    var liveTitle :String =""
    var anchorId :String =""

    var signIndex:Int=0
    var mShareBean : MaterialBean?= null

    var targetId :String =""
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        bundle=intent.extras
        signIndex=bundle!!.getInt("signIndex")
        url=bundle!!.getString("url","")
        liveID=bundle!!.getString("liveID","")
        userNick=bundle!!.getString("userNick","")
        userAvatar=bundle!!.getString("userAvatar","")
        coverUrl=bundle!!.getString("coverUrl","")
        liveTitle=bundle!!.getString("liveTitle","")
        anchorId=bundle!!.getString("anchorId","")
        if (signIndex==2)
            mShareBean= bundle!!.getSerializable("bean") as MaterialBean?
        if (signIndex==3 || signIndex==4)
            targetId=bundle!!.getString("targetId","")
        binding.bar.topLeftView.setSingleClickListener { finish() }
        binding.bar.topTitle.text="我的群"
        binding.llSearch.visibility= View.GONE
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->


            if (signIndex==1){
                if (TextUtils.isEmpty(url))
                    return@setOnItemClickListener
                val account = mAdapter.getItem(position).tid
                // 以单聊类型为例
                val sessionType = SessionTypeEnum.Team
                val custBean = CusShareLiveAttachment()
                custBean.userId=anchorId
                custBean.nickName=userNick
                custBean.headImg=userAvatar

                custBean.title=liveTitle
                custBean.imgCover=coverUrl
                custBean.liveUrl=url
                custBean.liveId=liveID
                custBean.anchorId=anchorId
                //标签
                custBean.tags=""
                //添加代理
                custBean.agent= ""
               // 创建一个自定义消息
                val custMsg = MessageBuilder.createCustomMessage(account,sessionType,custBean)
                // 发送给对方
                NIMClient.getService(MsgService::class.java).sendMessage(custMsg, true)
                    .setCallback(object : RequestCallback<Void> {
                        override fun onSuccess(result: Void?) {
                            showToast("分享成功...")
                            if (!LiveBlackList.isTaskShare && LiveBlackList.lastShareId!=mAdapter.getItem(position).gid){
                                LiveBlackList.lastShareId =mAdapter.getItem(position).gid
                            }
                            finish()
                        }

                        override fun onFailed(code: Int) {
                        }

                        override fun onException(exception: Throwable?) {
                        }

                    })
            }else if(signIndex==2){
                if (mShareBean==null)
                    return@setOnItemClickListener
                mShareBean?.let {
                    val materialChildList = mutableListOf<MaterialChildInfoBean>()
                    if (it.images.isNotEmpty()){
                        it.images.forEach {
                            materialChildList.add(MaterialChildInfoBean(0,it.url))
                        }
                    }
                    if (it.videos.isNotEmpty()){
                        it.videos.forEach {
                            materialChildList.add(MaterialChildInfoBean(1,it.url))
                        }
                    }
                    val account = mAdapter.getItem(position).tid
                    // 以单聊类型为例
                    val sessionType = SessionTypeEnum.Team
                    val custBean = CusShareSourceAttachment()
                    custBean.contentX=it.content
                    custBean.crt_time=it.publish_time
                    custBean.headimg=it.headimg
                    custBean.id=it.id
                    custBean.images=if(materialChildList.size>0) Gson().toJson(materialChildList)   else ""
                    custBean.nickname=it.nickname
                    custBean.uid=it.uid
                    // 创建一个自定义消息
                    val custMsg = MessageBuilder.createCustomMessage(account,sessionType,custBean)
                    // 发送给对方
                    NIMClient.getService(MsgService::class.java).sendMessage(custMsg, true)
                        .setCallback(object : RequestCallback<Void> {
                            override fun onSuccess(result: Void?) {
                                showToast("分享成功...")
                                finish()
                            }

                            override fun onFailed(code: Int) {
                            }

                            override fun onException(exception: Throwable?) {
                            }

                        })
                }
            }else  if(signIndex==3){
                //发送个人名片
//                val map: HashMap<String, Any> = HashMap()
//                map["type"] = 1
//                map["send_uid"] = targetId
//                map["send_gid"] = ""
//                map["received_gid"] = mAdapter.getItem(position).gid
//                loge("参数="+map.toString())
//                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShareBusinessCardMethod(it1) }
//                finish()
            }else  if(signIndex==4){
                //发送群名片
//                val map: HashMap<String, Any> = HashMap()
//                map["type"] = 2
//                map["send_uid"] = ""
//                map["send_gid"] = targetId
//                map["received_gid"] = mAdapter.getItem(position).gid
//                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onShareBusinessCardMethod(it1) }
//                finish()
            }



        }
        initRefreshLayout()
        pageNo = 1
        getListData()

    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    override fun initData() {
        super.initData()
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }
        }
    }


    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onMyGroupListMethod(it1) }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ShareGroupListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@ShareGroupListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

//            onShareBusinessCardData.observe(this@ShareGroupListActivity){
//                showToast("分享成功")
//            }

            onMyGroupListData.observe(this@ShareGroupListActivity) {
                //我的群聊 列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData( it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData( it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }
        }
    }


    inner class SearchChatAdapter   : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.friends_item) {
        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName,item.name)
                .setGone(R.id.tvBtnNext,true)

//            if (!TextUtils.isEmpty(item.shenhecnt)){
//                helper.setGone(R.id.tvBtnShenHe,false)
//                    .setText(R.id.tvBtnShenHe,item.shenhecnt)
//            }else helper.setGone(R.id.tvBtnShenHe,true)
        }
    }
}